package org.fq.log;

import java.io.File;
import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class LoggerInit {

    static {
        try {
        	initCurLogger();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final Logger logger = Logger.getLogger("jqueue");
    
    static private void initCurLogger() {
        DOMConfigurator.configure(LoggerInit.class.getClassLoader().getResource("jqueue_log4j.xml"));
        
        Logger logger = Logger.getLogger("jqueue");
        FileAppender bizFileAppender = getFileAppender(Logger.getRootLogger());
        if (null == bizFileAppender) {
        	logger.error("Logger can't find the 'FileAppender'.");
            return;
        }
        
        FileAppender selfFileAppender = getFileAppender(logger);
        String bizLogDir = new File(bizFileAppender.getFile()).getParent();
        String logFile = new File(bizLogDir, "jqueue.log").getAbsolutePath();
        selfFileAppender.setFile(logFile);
        selfFileAppender.activateOptions();
        AsyncAppender asynAppender = new AsyncAppender();
        asynAppender.addAppender(selfFileAppender);
        logger.addAppender(asynAppender);
        logger.removeAppender(selfFileAppender);
    }

    static private FileAppender getFileAppender(Logger logger) {
        FileAppender fileAppender = null;
        for (Enumeration<?> appenders = logger.getAllAppenders(); appenders.hasMoreElements();) {
            Appender appender = (Appender) appenders.nextElement();
            if (FileAppender.class.isInstance(appender)) {
                fileAppender = (FileAppender) appender;
            }
            if(fileAppender!=null) break;
        }
        return fileAppender;
    }

}
